<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\UsersService;
use app\admin\service\UsersWithdrawalLogService;
use app\AdminController;
use app\admin\service\WithdrawService;
use think\facade\Log;
use wxpay\Wxtransfer;

/**
 * 提现管理
 * Class Withdraw
 * @package app\admin\controller
 */
class Withdraw extends AdminController
{
    /**
     * 提现列表
     * @return \think\response\Json|\think\response\View
     */
    public function index()
    {
        if (request()->isPost()) {
            $where = [];
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($keywords) {
                $where[] = ['w.w_sn|u.nickname', 'like', '%' . $keywords . '%'];
            }

            // 状态搜索
            $status = $this->request->param('status', '-1');
            if ($status != '-1') {
                $where[] = ['w.status', '=', $status];
            }

            $list = WithdrawService::getWithdrawList($where, $this->page, $this->pagesize);
            $count = WithdrawService::countWithdrawList($where);
            return adminResponseJson(['list' => $list, 'count' => $count]);
        }

        return view();
    }

    /**
     * 提现打款
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payment()
    {
        if (request()->isPost()) {
            $id = intval($this->request->param('id', 0));
            if (!$id) {
                $this->error(adminJsonMsg(1001));
            }

            // 查询当前数据
            $where = ['id' => $id];
            $info = WithdrawService::findWithdraw($where);
            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            if ($info['status']) {
                $this->error(adminJsonMsg(10022));
            }

            // 查询用户openid
            $pub_openid = UsersService::findUsersValue(['id' => $info['links_id']]);
            if (!$pub_openid) {
                $this->error(adminJsonMsg(10023));
            }

            // 发送模板消息
            $pay = new Wxtransfer();
            $return = json_decode($pay->pay($pub_openid, $info['money'], $desc = '云链路提现打款'), true);
            if ($return['result_code'] == 'FAIL') {
                Log::write('打款失败' . json_encode($return), 'error');
                $this->error(adminJsonMsg(10024));
            }

            // 更新提现表
            $status = 1;
            $remit_time = time();
            WithdrawService::updateWithdraw($where, ['status' => $status, 'remit_time' => $remit_time, 'm_sn' => 'M' . generateOrderNo()]);

            // 创建用户提现记录
//            UsersWithdrawalLogService::createUsersWithdrawalLog([
//                'uid' => $info['links_id'],
//                'title' => $info['desc'],
//                'sub_title' => '成功提现到微信钱包',
//                'money' => $info['money'],
//                'withdrawal' => '-' . $info['money'],
//                'status' => $status,
//                // 是否内网提现
//                'is_intranet' => $info['wid'] ? 1 : 0,
//                'create_time' => strtotime($info['create_time']),
//                'update_time' => $info['update_time'] ? strtotime($info['update_time']) : 0,
//                'remit_time' => $remit_time,
//                'reason' => $info['reason'],
//                'reject_time' => $info['reject_time'],
//            ]);

            $this->success(adminJsonMsg(1004));
        }
    }

    /**
     * 驳回提现申请
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function reject()
    {
        if (request()->isPost()) {
            $id = intval($this->request->param('id', 0));
            $reason = trim($this->request->param('reason', ''));
            if (!$id || !$reason) {
                $this->error(adminJsonMsg(1001));
            }

            // 查询当前数据
            $where = ['id' => $id];
            $info = WithdrawService::findWithdraw($where);
            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            $status = 2;
            $reject_time = time();
            $res = WithdrawService::updateWithdraw($where, ['status' => $status, 'reject_time' => $reject_time, 'reason' => $reason]);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            // 创建用户提现记录
//            UsersWithdrawalLogService::createUsersWithdrawalLog([
//                'uid' => $info['links_id'],
//                'title' => $info['desc'],
//                'sub_title' => '成功提现到微信钱包',
//                'money' => $info['money'],
//                'withdrawal' => '-' . $info['money'],
//                'status' => $status,
//                // 是否内网提现
//                'is_intranet' => $info['wid'] ? 1 : 0,
//                'create_time' => strtotime($info['create_time']),
//                'update_time' => $info['update_time'] ? strtotime($info['update_time']) : 0,
//                'remit_time' => $info['remit_time'],
//                'reason' => $reason,
//                'reject_time' => $reject_time,
//            ]);

            $this->success(adminJsonMsg(1004));
        }
    }
}